package org.zh.sh.util.create;

import com.mysql.cj.MysqlType;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MysqlTablesInfo implements TablesInfo {

    public static final  MysqlTablesInfo info = new MysqlTablesInfo();

    @Override
    public  List<String> showTables(Connection conn) throws SQLException {
        List<String> list = new ArrayList<>();
        String sql = "show tables";
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        while (rs.next()) {
            list.add(rs.getString(1));
        }
        rs.close();
        st.close();
        return list;
    }


    @Override
    public List<TableInfo> allColumnsInfo(Collection<String> tableNames, Connection conn) throws SQLException {
        String sql = "select COLUMN_NAME,COLUMN_TYPE,COLUMN_COMMENT,COLUMN_KEY,EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME = ?";
        List<TableInfo> tas = new ArrayList<>();
        ResultSet rs = null;
        PreparedStatement ps = null;
        for (String tb : tableNames) {
            ps = conn.prepareStatement(sql);
            ps.setString(1, tb);
            rs = ps.executeQuery();
            List<ColumnInfo> list = new ArrayList<>();
            while (rs.next()) {
                String COLUMN_NAME = rs.getString(1);
                String COLUMN_TYPE = rs.getString(2);
                String COLUMN_COMMENT = rs.getString(3);
                String COLUMN_KEY = rs.getString(4);
                String EXTRA = rs.getString(5);
                ColumnInfo info = new ColumnInfo(COLUMN_NAME, COLUMN_TYPE, mysqlJavaType(COLUMN_TYPE), clazzAlias(COLUMN_NAME), COLUMN_COMMENT, mysqlPri.equals(COLUMN_KEY), mysql_auto.equals(EXTRA));
                list.add(info);
            }
            TableInfo tableInfo = new TableInfo(tb, clazzName(tb), clazzAlias(tb), list);
            tas.add(tableInfo);
        }
        assert ps != null;
        rs.close();
        ps.close();
        return tas;
    }

    @Override
    public TableInfo columnsInfo(String tableName, Connection conn) throws SQLException {
      return  allColumnsInfo(Collections.singleton(tableName),conn).getFirst();
    }

    @Override
    public List<String> tablePri(String tableName, Connection conn) throws SQLException {
        TableInfo tableInfo = columnsInfo(tableName, conn);
        List<String> list = new ArrayList<>();
       for (ColumnInfo columnInfo:tableInfo.columns()){
           if(columnInfo.autoincrement()){
               list.add(columnInfo.columnName());
           }
       }
        return list;
    }

    private static String mysqlJavaType(String COLUMN_TYPE) {
        MysqlType mysqlType = MysqlType.getByName(COLUMN_TYPE);
        return mysqlType.getClassName();
    }

}
